from flask import Flask
from exts import db
from flask_migrate import Migrate
from models import Article,User,UserExtension
import config


app = Flask(__name__)
app.config.from_object(config)
#把app绑定到db = SQLAlchemy()
db.init_app(app)
migrate = Migrate(app,db)


@app.route("/otm")
def one_to_many():
    #article = Article(title="111",content="xxx")
    article1 = Article(title="001", content="三国")
    article2 = Article(title="002", content="水浒")
    user = User(username="zhiliao")
    #article.author = user
    article1.author = user
    article2.author = user
    db.session.add(article1,article2)
    db.session.commit()

    print(user.articles)
    return "otm数据库操作成功"


@app.route("/oto")
def one_to_one():
    #fist()和[0]可以取出第一条数据
    user = User(username="lihua")
    #user = User.query.filter_by(id = 1).first()
    extension = UserExtension(school="清华大学")
    user.extension = extension
    db.session.add(user)
    db.session.commit()
    return "one to one success"


@app.route("/article")
def article_view():
    # #1添加数据
    # #insert table article values(xx)
    # article = Article(title="钢铁是怎样炼成的",content='xxx')
    # db.session.add(article)
    # #一个提交操作
    # db.session.commit()

    # #2.查询操作
    # #filter_by:返回一个类列表的对象
    # article = Article.query.filter_by(id=1)[0]
    # print(article.title)

    # #3.修改数据
    #     # article = Article.query.filter_by(id=1)[0]
    #     # article.content = "yyy"
    #     # db.session.commit()

    #4.删除数据
    # Article.query.filter_by(id=1).delete()
    # db.session.commit()

    return "数据成功"

@app.route('/')
def hello_world():
    #测试代码是否连接成功
    engine = db.get_engine()
    with engine.connect() as conn:
        result = conn.execute("select 1")
        print(result.fetchone())
    return 'Hello World!'


if __name__ == '__main__':
    app.run()
